package ivan.cheng.tuqu.activity;

import ivan.cheng.tuqu.Globals;
import ivan.cheng.tuqu.R;
import ivan.cheng.tuqu.crop.CropImage;
import ivan.cheng.tuqu.util.FileUtil;
import ivan.cheng.tuqu.util.LogUtil;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.TrafficStats;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

	private static final int REQUEST_CODE_CAMERA = 10;//通过相机获取
	private static final int REQUEST_CODE_GALLERY = 11;//通过照片获取
	private static final int REQUEST_CODE_CROP_MSG = 12;
	private File mCameraTempFile;//存放拍照回来后的临时文件
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.iv_photograph).setOnClickListener(this);
        findViewById(R.id.btn_gallery).setOnClickListener(this);
        CreateDir();
//        long count = getMobileRxBytes();
//        long time = SystemClock.elapsedRealtime()/1000;
//        this.toString();
    }

    /**
	 *@函数说明： 检查是否有SD卡，并创建目录
	 */
	private void CreateDir() {
		if (FileUtil.getInstance().haveSD()) {

			FileUtil.mkdir(Globals.MX_FILE_PATH_HOME);
			FileUtil.mkdir(Globals.MX_FILE_PATH_SAVE);
			FileUtil.mkdir(Globals.MX_FILE_PATH_HEAD);
			FileUtil.mkdir(Globals.MX_FILE_PATH_ZOOM_IN);
			FileUtil.mkdir(Globals.MX_FILE_PATH_ZOOM_OUT);
			FileUtil.mkdir(Globals.MX_FILE_PATH_DSIPOSE); // 处理后的文件照片
			FileUtil.mkdir(Globals.MX_FILE_PATH_SPEC_EFFECT); // 特效
			FileUtil.mkdir(Globals.MX_FILE_PATH_SPEC_EFFECT_ADORM); // 特效装饰恶搞 表情
			FileUtil.mkdir(Globals.MX_FILE_PATH_SPEC_EFFECT_FOAM); // 特效文字泡泡表情
			FileUtil.mkdir(Globals.MX_FILE_PATH_SPEC_EFFECT_PIC); // 特效拼图相框表情
			FileUtil.mkdir(Globals.MX_FILE_PATH_THEME); // 节日主题
			FileUtil.mkdir(Globals.MX_FILE_PATH_THEME_ADORM); // 装饰恶搞表情
			FileUtil.mkdir(Globals.MX_FILE_PATH_THEME_FOAM); // 文字泡泡表情
			FileUtil.mkdir(Globals.MX_FILE_PATH_THEME_PIC); // 拼图相框表情
			FileUtil.mkdir(Globals.MX_FILE_PATH_SPEC_EFFECT_IMG); // 特效缩略图
			FileUtil.mkdir(Globals.MX_FILE_PATH_THME_IMG); // 主题缩略图
			FileUtil.mkdir(Globals.MX_FILE_VERSION_PATH); // 版本号
			
			if ((FileUtil.getInstance().getSDSize()/(1024*1024))< 20) {
				Toast.makeText(this,getText(R.string.memory_tips), Toast.LENGTH_SHORT).show();
			}
			
		} else
			Toast.makeText(this, getString(R.string.sd_exsit),
					Toast.LENGTH_SHORT).show();
	}
    
    protected void StartCropImage(String imgPath, boolean bFromCamera) {
		Intent intent = new Intent();
		Bundle myConcernbl = new Bundle();
		intent.setClass(this, CropImage.class);
		myConcernbl.putBoolean("return-data", true);
		myConcernbl.putString(Globals.EXTRA_PHOTO_PATH,imgPath);
		myConcernbl.putBoolean(Globals.EXTRA_IMAGE_SOURCE, bFromCamera);
		intent.putExtras(myConcernbl);
		startActivityForResult(intent, REQUEST_CODE_CROP_MSG);
	}
    
    private void StartCamera() {
		// 调用相机
		Intent i_camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// 图片存储路径，可自定义
		String fName = /*System.currentTimeMillis()*/"tuqutemp" + ".jpg";
		mCameraTempFile = new File(Globals.MX_FILE_PATH_SAVE + fName);

		// 获取这个图片的URI
		Uri cameraUri = Uri.fromFile(mCameraTempFile);// 这是个实例变量，方便下面获取图片的时候用
		i_camera.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
		i_camera.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 512*512);
		i_camera.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
		startActivityForResult(i_camera,
				REQUEST_CODE_CAMERA);
		
	}
    
	@Override
	public void onClick(View v) 
	{
		switch (v.getId()) 
		{
		case R.id.btn_gallery:
		{
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            startActivityForResult(intent, REQUEST_CODE_GALLERY);
		}
			break;
		case R.id.iv_photograph:
			StartCamera();
			break;

		default:
			break;
		}
	}
	
	protected void startEffectProcessingActivity(Bundle bundle,boolean iscamera) {
		Intent intent = new Intent(this, EffectsProcessingActivity.class);
		intent.putExtras(bundle);
		startActivity(intent);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		if (Activity.RESULT_OK != resultCode) 
		{
			return;
		}

		Bundle bd = null;
		if (data != null)
			bd = data.getExtras();

		switch (requestCode) {
		case REQUEST_CODE_CAMERA:
			if(mCameraTempFile.length()<=0)
			{
				return;
			}
			StartCropImage(mCameraTempFile.getPath(),true);
			break;
		case REQUEST_CODE_GALLERY:
        	if (resultCode != RESULT_OK) {return;}
        	if (data == null) {
                return;
            }
        	
        	Uri url= data.getData();
        	String imgPath = null;
         	if (url.toString().startsWith("content://")) {
            	Cursor cursor = getContentResolver().query(url, null, null, null, null);
               	if (cursor ==null) {
					return;
				}
            	cursor.moveToFirst();
                imgPath = cursor.getString(1);      //图片文件路径
            
               
         	}else if( url.toString().startsWith("file://") ){
				imgPath = url.toString().replace("file://", "");					 
			}else if( url.toString().startsWith("data://") ){
				imgPath = url.toString().replace("data://", "");					 
			}else 
			{
				LogUtil.i("File Error: " + url.toString());
				return;
			}
			LogUtil.i("imgPath: " + imgPath);
			
			StartCropImage(imgPath,false);
        	break;
        case REQUEST_CODE_CROP_MSG:
            {
            	if (resultCode != RESULT_OK) 
            	{          	 
            		 return;
            	}
            	if(null != data)
            	{
//            		//Bitmap bmp = (Bitmap)data.getExtras().getParcelable("data");
//            		if (picCategoryString.equals(PHOTOGRAPHCATE_SET_AVATAR)){
//        				
//        	            //修改头像
//        	            Intent intent = new Intent();
//        	            //Bundle bd = new Bundle();
//        	            //bd.putParcelable(Globals.STRING_CONSTANT_CONTENT, bmp);
//        	    		//intent.putExtra(Globals.EXTRA_PHOTO_PATH, filePathString);
//        	            intent.putExtras(data.getExtras());
//        	            setResult(Activity.RESULT_OK, intent);
//        	    		finish();
//        			}else{
        				startEffectProcessingActivity(data.getExtras(),false);
 //       			}
            		
            		
            	}
            }
        	break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	
	public long getTotalRxBytes(){  //获取总的接受字节数，包含Mobile和WiFi等  
        return TrafficStats.getTotalRxBytes()==TrafficStats.UNSUPPORTED?0:(TrafficStats.getTotalRxBytes()/1024);  
    }  
    public long getTotalTxBytes(){  //总的发送字节数，包含Mobile和WiFi等  
        return TrafficStats.getTotalTxBytes()==TrafficStats.UNSUPPORTED?0:(TrafficStats.getTotalTxBytes()/1024);  
    }  
    public long getMobileRxBytes(){  //获取通过Mobile连接收到的字节总数，不包含WiFi  
        return TrafficStats.getMobileRxBytes()==TrafficStats.UNSUPPORTED?0:(TrafficStats.getMobileRxBytes()/1024);  
    }  
}
